package org.dromara.business.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.User;
import org.dromara.business.domain.bo.LotteryRecordsBo;
import org.dromara.business.domain.bo.UserBo;
import org.dromara.business.domain.vo.UserVo;
import org.dromara.business.mapper.UserMapper;
import org.dromara.business.service.BusinessConfigTypeService;
import org.dromara.business.service.LotteryRecordsService;
import org.dromara.business.service.UserFlowingService;
import org.dromara.business.service.UserService;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户信息Service业务层处理
 *
 * @author zlj
 * @date 2024-11-19
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper baseMapper;
    private final UserFlowingService userFlowingService;
    private final LotteryRecordsService lotteryRecordsService;

    /**
     * 查询用户信息
     */
    @Override
    public UserVo queryById(Long userId) {
        return baseMapper.selectVoById(userId);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public TableDataInfo<UserVo> queryPageList(UserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public List<UserVo> queryList(UserBo bo) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<User> buildQueryWrapper(UserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, User::getDeptId, bo.getDeptId());
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), User::getUserName, bo.getUserName());
        lqw.like(StrUtil.isNotBlank(bo.getNickName()), User::getNickName, bo.getNickName());
        lqw.eq(StrUtil.isNotBlank(bo.getUserType()), User::getUserType, bo.getUserType());
        lqw.eq(StrUtil.isNotBlank(bo.getEmail()), User::getEmail, bo.getEmail());
        lqw.eq(StrUtil.isNotBlank(bo.getPhonenumber()), User::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StrUtil.isNotBlank(bo.getOpenid()), User::getOpenid, bo.getOpenid());
        lqw.eq(StrUtil.isNotBlank(bo.getUnionid()), User::getUnionid, bo.getUnionid());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), User::getSex, bo.getSex());
//        lqw.eq(bo.getAvatar() != null, User::getAvatar, bo.getAvatar());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), User::getPassword, bo.getPassword());
//        lqw.eq(bo.getAmount() != null, User::getAmount, bo.getAmount());

        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), User::getStatus, bo.getStatus());
        lqw.orderByDesc(User::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户信息
     */
    @Override
    public Boolean insertByBo(UserBo bo) {
        User add = MapstructUtils.convert(bo, User.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户信息
     */
    @Override
    public Boolean updateByBo(UserBo bo) {
        User update = MapstructUtils.convert(bo, User.class);
        validEntityBeforeSave(update);
        if (LoginHelper.getUserType().getUserType().equals(UserType.XCX_USER.getUserType())) {
            update.setUserId(LoginHelper.getUserId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(User entity) {

    }

    /**
     * 批量删除用户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int gqTimeUpdate(String date) {
                Long userId = LoginHelper.getUserId();
        User user = this.getById(userId);
        user.setNumberDraws(user.getNumberDraws() - 1);
        if ("感谢参与".equals(date)) {
            return baseMapper.updateById(user);
        }
        Integer daysToAdd = extractNumber(date);
        int i = baseMapper.updateById(user);
        userFlowingService.addAmount(LoginHelper.getUserId(), new BigDecimal(daysToAdd), BusinessConstants.FLOWING_TYPE_SIGN, null);
//        // 新增抽奖记录
        LotteryRecordsBo lotteryRecordsBo = new LotteryRecordsBo();
        lotteryRecordsBo.setAward(date);
        lotteryRecordsBo.setCreateBy(userId);
        lotteryRecordsBo.setCreateTime(new Date());
        lotteryRecordsService.insertByBo(lotteryRecordsBo);
        return  i;


    }

    public static Integer extractNumber(String input) {
        // 定义正则表达式模式，匹配一个或多个数字
        String regex = "\\d+";

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建匹配器
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            // 提取并解析数字
            return Integer.parseInt(matcher.group());
        } else {
            throw new ServiceException("转盘奖品配置错误");

        }
    }

    // 辅助方法：将 Date 转换为 LocalDateTime
    private LocalDateTime convertToLocalDateTime(Date date, LocalDateTime currentTime) {
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        if (localDateTime.isBefore(currentTime)) {
            return currentTime;
        }else {
            return localDateTime;
        }
    }
}
